﻿using UnityEngine;
using System.Collections;

[RequireComponent (typeof(Light))]
public class SpotlightSensor : LightSensor {
    
    public float Distance = 1.0f;

    // Use this for initialization
    void Start () {
        AddLight(this);
    }
    
    // Update is called once per frame
    void Update () {
    
    }

    public override bool IsInLight(Vector3 position, GameObject targetObject) {
        if (!light.enabled) {
            return false;
        }
        Vector3 originPoint = transform.position;
        Vector3 lightDirection = transform.forward;

        Vector3 delta = position - originPoint;
        // distance test
        if (delta.sqrMagnitude > Distance * Distance) {
            return false;
        }
        // angle test
        if (Vector3.Angle(delta, lightDirection) > light.spotAngle / 2.0f) {
            return false;
        }
        // raycast test, return false if hit other object
        RaycastHit hit;
        if (Physics.Raycast(originPoint, delta, out hit, Distance)) {
            if (hit.collider.gameObject == targetObject) {
                return true;
            }
            return false;
        }
        return true;
    
    }

}
